import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/index.vue'
import cookies from '@/utils/cookies'
import UserManage from '@/views/user/user.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home
  },
  {
    path: '/user',
    component: UserManage
  }
]

const router = new VueRouter({
  routes
})
const whiteList = ['/login']
// 路由前置守卫
router.beforeEach((to, from, next) => {
  // console.log('to',to);
  // to.path === "/" ||
  // if (to.path === "/login") return next();

  const hasToken = cookies.getToken()
  // console.log('hasToken',hasToken);

  // 已登陆
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
      // const hasGetUserInfo = store.getters.name
      // if (hasGetUserInfo) {
      //    next()
      // } else {
      //   try {
      //     // get user info
      //     // await store.dispatch('user/getInfo')

      //     next()
      //   } catch (error) {
      //     // await store.dispatch('user/resetToken')
      //     // Message.error({ message: error || "Has Error" })
      //     next(`/login?redirect=${to.path}`)
      //   }
      // }
    }
  } else {
    if (whiteList.indexOf(to.path) > -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})
// router.afterEach((from, to) => {});
export default router
